package com.ai.core.http;

import java.io.IOException;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.ai.core.util.Configure;

/**
 * 流量云HTTP接口
 * 
 * @author wangly
 * 
 */

public final class FlowCloudHttpPostHelper {
	private static Log log = LogFactory.getLog(FlowCloudHttpPostHelper.class);
	private static String flowCloudUrl = null;
	private static String sellId = null;
	private static String key = null;
	static {
		try {
			flowCloudUrl = Configure.getString("flow_cloud_url");
			sellId = Configure.getString("sell_id");
			key = Configure.getString("key");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static String getTimeStamp() {

		Calendar cal = Calendar.getInstance();
		java.util.Date date = cal.getTime();

		SimpleDateFormat sdFormat = new SimpleDateFormat("yyyyMMddhhmmssSSS");
 
		return  sdFormat.format(date);
	}

	public static void main(String[] args) throws Exception {
		doPost("1891659585", "103132", getTimeStamp()); 
	}

	public static String doPost(String mobile, String productId, String timeStamp) throws Exception {

		StringBuffer response = new StringBuffer();
		HttpClient client = new HttpClient();
		PostMethod postMethod = new PostMethod(flowCloudUrl);
		postMethod.setRequestHeader(new Header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"));

		String url_parm = getUrlParam(mobile, productId, key);
		String sig = getSig(sellId, timeStamp, mobile, productId, key);
		postMethod.addParameter("url_parm", url_parm);
		postMethod.addParameter("sell_id", sellId);
		postMethod.addParameter("timeStamp", timeStamp);
		postMethod.addParameter("sig", sig);
		log.info("url_parm="+url_parm+"&sell_id="+sellId+"&timeStamp="+timeStamp+"&sig="+sig);
		System.out.println("url_parm="+url_parm+"&sell_id="+sellId+"&timeStamp="+timeStamp+"&sig="+sig);
		try {
			int status = client.executeMethod(postMethod);

			if (status == HttpStatus.SC_OK) {
				String json = new String(postMethod.getResponseBody(), "GBK");
				System.out.println(json);
				return json;
			} else {
				throw new Exception("连接失败");
			}
		} catch (IOException e) {
			e.printStackTrace();
			log.error("执行HTTP Post请求" + flowCloudUrl + "时，发生异常！", e);
		} finally {
			postMethod.releaseConnection();
		}
		return response.toString();
	}

	public static String encodeDes(String key, String strUrl) {
		try {
			Cipher cipher = getDesCipher(key, "encrypt");
			return byteArr2HexStr(cipher.doFinal(strUrl.getBytes("utf-8")));
		} catch (Exception e) {
			e.printStackTrace();
			// LOG.error("加密DES[" + strIn + "]失败", e);
		}
		return null;
	}

	public static String byteArr2HexStr(byte[] arrB) throws Exception {
		int iLen = arrB.length;
		StringBuffer sb = new StringBuffer(iLen * 2);
		for (int i = 0; i < iLen; i++) {
			int intTmp = arrB[i];
			while (intTmp < 0) {
				intTmp += 256;
			}
			if (intTmp < 16) {
				sb.append("0");
			}
			sb.append(Integer.toString(intTmp, 16).toUpperCase());
		}
		return sb.toString();
	}

	private static Cipher getDesCipher(String key, String type) {
		Cipher cipher = null;
		try {
			DESKeySpec dks = new DESKeySpec(key.getBytes());
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			SecretKey secretKey = keyFactory.generateSecret(dks);
			cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
			if ("encrypt".equals(type))
				cipher.init(1, secretKey);
			else
				cipher.init(2, secretKey);
		} catch (Exception e) {
			e.printStackTrace();
			// LOG.error("初始化DES-Cipher失败", e);
		}
		return cipher;
	}

	// MD5加密函数
	public static String MD5Encode(String sourceString) {
		byte[] bytes = null;
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			bytes = md5.digest(sourceString.toString().getBytes("UTF-8"));
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		// 将MD5输出的二进制结果转换为小写的十六进制
		StringBuilder sign_s = new StringBuilder();
		for (int i = 0; i < bytes.length; i++) {
			String hex = Integer.toHexString(bytes[i] & 0xFF);
			if (hex.length() == 1) {
				sign_s.append("0");
			}
			sign_s.append(hex);
		}
		return sign_s.toString();
	}

	/**
	 * 获取加密后的urlParam
	 * 
	 * @param mobile
	 * @param productId
	 * @return
	 */
	private static String getUrlParam(String mobile, String productId, String urlParamKey) {
		String urlParam = "mobile=" + mobile + "&productid=" + productId;
		return encodeDes(urlParamKey, urlParam);
	}

	/**
	 * 获取加密的sig
	 * 
	 * @param sellId
	 * @param timeStamp
	 * @param key
	 * @param mobile
	 * @param productId
	 * @param sigKey
	 * @return
	 */
	private static String getSig(String sellId, String timeStamp, String mobile, String productId, String sigKey) {
		String sig = mobile + "||" + sellId + "||" + timeStamp + "||" + productId + "||" + sigKey;
		return MD5Encode(sig);
	}

}
